{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1a4596ea-a631-416d-a2a4-3577c140493d",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Tracing and Datasets with LangChainPlus\n",
    "\n",
    "LangChain makes it easy to get started with Agents and other LLM applications. However, it can be tricky to get right, especially when you need to deliver a full product. To speed up your application development process, and to help monitor your applications in production, LangChain offers additional tracing and tooling.\n",
    "\n",
    "When might you want to use tracing? Some situations we've found it useful include:\n",
    "- Quickly debugging a new chain, agent, or set of tools\n",
    "- Evaluating a given chain across different LLMs or Chat Models to compare results or improve prompts\n",
    "- Running a given chain multiple time on a dataset to ensure it consistently meets a quality bar.\n",
    "\n",
    "\n",
    "In this notebook, we'll show how to enable tracing in your LangChain applications and walk you a couple common ways to evaluate your agents.\n",
    "We'll focus on using Datasets to benchmark Chain behavior.\n",
    "\n",
    "**Bear in mind that this notebook is designed under the assumption that you're running the latest LangChain+ server locally in the background. This is done using the folowing command in your terminal:**\n",
    "\n",
    "\n",
    "```\n",
    "pip install --upgrade langchain\n",
    "langchain plus start\n",
    "```\n",
    "\n",
    "We also have a hosted version which is in private beta. We will share more details as it progresses.\n",
    "\n",
    "Now, let's get started by creating a client to connect to LangChain+."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d77d064-41b4-41fb-82e6-2d16461269ec",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Setting up Tracing\n",
    "\n",
    "The V2 tracing API can be activated by setting the `LANGCHAIN_TRACING_V2` environment variable to true. Assuming you've successfully initiated the server as described earlier, running LangChain Agents, Chains, LLMs, and other primitives will automatically start capturing traces. Let's begin our exploration with a straightforward math example.\n",
    "\n",
    "**NOTE**: You must also set your `OPENAI_API_KEY` and `SERPAPI_API_KEY` environment variables in order to run the following tutorial.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7935e832-9ae1-4557-8d08-890c425f18e2",
   "metadata": {},
   "source": [
    "**NOTE:** You can also use the `tracing_v2_enabled` context manager to capture sessions within a given context:\n",
    "```\n",
    "from langchain.callbacks.manager import tracing_v2_enabled\n",
    "with tracing_v2_enabled(\"My Session Name\"):\n",
    "    ...\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "221b638a-2ae4-46ef-bf6a-d59bf85d587f",
   "metadata": {},
   "source": [
    "**NOTE:** You can optionally set the `LANGCHAIN_ENDPOINT` and `LANGCHAIN_API_KEY` environment variables if using the hosted version which is in private beta."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "904db9a5-f387-4a57-914c-c8af8d39e249",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You can click the link below to view the UI\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<a href=\"https://dev.langchain.plus\", target=\"_blank\" rel=\"noopener\">LangChain+ Client</a>"
      ],
      "text/plain": [
       "LangChainPlusClient (API URL: https://dev.api.langchain.plus)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "from langchainplus_sdk import LangChainPlusClient\n",
    "from langchain.client import arun_on_dataset, run_on_dataset\n",
    "\n",
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_SESSION\"] = \"Tracing Walkthrough\"\n",
    "# os.environ[\"LANGCHAIN_ENDPOINT\"] = \"https://api.langchain.plus\"  # Uncomment this line if you want to use the hosted version\n",
    "# os.environ[\"LANGCHAIN_API_KEY\"] = \"<YOUR-LANGCHAINPLUS-API-KEY>\"  # Uncomment this line if you want to use the hosted version.\n",
    "\n",
    "client = LangChainPlusClient()\n",
    "print(\"You can click the link below to view the UI\")\n",
    "client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7c801853-8e96-404d-984c-51ace59cbbef",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.agents import initialize_agent, load_tools\n",
    "from langchain.agents import AgentType\n",
    "\n",
    "llm = ChatOpenAI(temperature=0)\n",
    "tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n",
    "agent = initialize_agent(\n",
    "    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "19537902-b95c-4390-80a4-f6c9a937081e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "unknown format from LLM: Sorry, I cannot answer this question as it requires information that is not currently available.\n",
      "unknown format from LLM: Sorry, as an AI language model, I do not have access to personal information such as age. Please provide a valid math problem.\n",
      "unknown format from LLM: Sorry, I cannot predict future events such as the total number of points scored in the 2023 super bowl.\n",
      "This model's maximum context length is 4097 tokens. However, your messages resulted in 4097 tokens. Please reduce the length of the messages.\n",
      "unknown format from LLM: This is not a math problem and cannot be translated into a mathematical expression.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['The population of Canada as of 2023 is estimated to be 39,566,248.',\n",
       " \"Anwar Hadid is Dua Lipa's boyfriend and his age raised to the 0.43 power is approximately 3.87.\",\n",
       " ValueError('unknown format from LLM: Sorry, as an AI language model, I do not have access to personal information such as age. Please provide a valid math problem.'),\n",
       " 'The distance between Paris and Boston is 3448 miles.',\n",
       " ValueError('unknown format from LLM: Sorry, I cannot answer this question as it requires information that is not currently available.'),\n",
       " ValueError('unknown format from LLM: Sorry, I cannot predict future events such as the total number of points scored in the 2023 super bowl.'),\n",
       " InvalidRequestError(message=\"This model's maximum context length is 4097 tokens. However, your messages resulted in 4097 tokens. Please reduce the length of the messages.\", param='messages', code='context_length_exceeded', http_status=400, request_id=None),\n",
       " '1.9347796717823205',\n",
       " ValueError('unknown format from LLM: This is not a math problem and cannot be translated into a mathematical expression.'),\n",
       " '0.2791714614499425']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import asyncio\n",
    "\n",
    "inputs = [\n",
    "    \"How many people live in canada as of 2023?\",\n",
    "    \"who is dua lipa's boyfriend? what is his age raised to the .43 power?\",\n",
    "    \"what is dua lipa's boyfriend age raised to the .43 power?\",\n",
    "    \"how far is it from paris to boston in miles\",\n",
    "    \"what was the total number of points scored in the 2023 super bowl? what is that number raised to the .23 power?\",\n",
    "    \"what was the total number of points scored in the 2023 super bowl raised to the .23 power?\",\n",
    "    \"how many more points were scored in the 2023 super bowl than in the 2022 super bowl?\",\n",
    "    \"what is 153 raised to .1312 power?\",\n",
    "    \"who is kendall jenner's boyfriend? what is his height (in inches) raised to .13 power?\",\n",
    "    \"what is 1213 divided by 4345?\",\n",
    "]\n",
    "results = []\n",
    "\n",
    "\n",
    "async def arun(agent, input_example):\n",
    "    try:\n",
    "        return await agent.arun(input_example)\n",
    "    except Exception as e:\n",
    "        # The agent sometimes makes mistakes! These will be captured by the tracing.\n",
    "        print(e)\n",
    "        return e\n",
    "\n",
    "\n",
    "for input_example in inputs:\n",
    "    results.append(arun(agent, input_example))\n",
    "await asyncio.gather(*results)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c43c311-4e09-4d57-9ef3-13afb96ff430",
   "metadata": {},
   "source": [
    "## Creating the Dataset\n",
    "\n",
    "Now that you've captured a session entitled 'Tracing Walkthrough', it's time to create a dataset. We will do so using the `create_dataset` method below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d14a9881-2a01-404c-8c56-0b78565c3ff4",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "dataset_name = \"calculator-example-dataset-2\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "17580c4b-bd04-4dde-9d21-9d4edd25b00d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "if dataset_name in set([dataset.name for dataset in client.list_datasets()]):\n",
    "    client.delete_dataset(dataset_name=dataset_name)\n",
    "dataset = client.create_dataset(\n",
    "    dataset_name, description=\"A calculator example dataset\"\n",
    ")\n",
    "runs = client.list_runs(\n",
    "    session_name=os.environ[\"LANGCHAIN_SESSION\"],\n",
    "    execution_order=1,  # Only return the top-level runs\n",
    "    error=False,  # Only runs that succeed\n",
    ")\n",
    "for run in runs:\n",
    "    try:\n",
    "        client.create_example(\n",
    "            inputs=run.inputs, outputs=run.outputs, dataset_id=dataset.id\n",
    "        )\n",
    "    except:\n",
    "        pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db79dea2-fbaa-4c12-9083-f6154b51e2d3",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "**Alternative: Creating a Dataset in the UI** \n",
    "\n",
    "Alternatively, you could create or edit the dataset in the UI using the following steps:\n",
    "\n",
    "   1. Navigate to the UI by clicking on the link below.\n",
    "   2. Select the 'search_and_math_chain' session from the list.\n",
    "   3. Next to the fist example, click \"+ to Dataset\".\n",
    "   4. Click \"Create Dataset\" and create a title **\"calculator-example-dataset\"**.\n",
    "   5. Add the other examples to the dataset as well\n",
    "\n",
    "Once you've used LangChain+ for a while, you will have a number of datasets to work with. To view all saved datasets, execute the following code:\n",
    "\n",
    "```\n",
    "datasets = client.list_datasets()\n",
    "print(datasets)\n",
    "```\n",
    "\n",
    "\n",
    "**Optional:** If you didn't run the trace above, you can also create datasets by uploading dataframes or CSV files."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1baa677c-5642-4378-8e01-3aa1647f19d6",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# !pip install datasets > /dev/null\n",
    "# !pip install pandas > /dev/null"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "60d14593-c61f-449f-a38f-772ca43707c2",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import pandas as pd\n",
    "# from langchain.evaluation.loading import load_dataset\n",
    "\n",
    "# dataset = load_dataset(\"agent-search-calculator\")\n",
    "# df = pd.DataFrame(dataset, columns=[\"question\", \"answer\"])\n",
    "# df.columns = [\"input\", \"output\"] # The chain we want to evaluate below expects inputs with the \"input\" key\n",
    "# df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "52a7ea76-79ca-4765-abf7-231e884040d6",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# dataset_name = \"calculator-example-dataset\"\n",
    "\n",
    "# if dataset_name not in set([dataset.name for dataset in client.list_datasets()]):\n",
    "#     dataset = client.upload_dataframe(df,\n",
    "#                             name=dataset_name,\n",
    "#                             description=\"A calculator example dataset\",\n",
    "#                             input_keys=[\"input\"],\n",
    "#                             output_keys=[\"output\"],\n",
    "#                    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07885b10",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Running a Chain on a Traced Dataset\n",
    "\n",
    "Once you have a dataset, you can run a compatible chain or other object over it to see its results. The run traces will automatically be associated with the dataset for easy attribution and analysis.\n",
    "\n",
    "**First, we'll define the chain we wish to run over the dataset.**\n",
    "\n",
    "In this case, we're using an agent, but it can be any simple chain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c2b59104-b90e-466a-b7ea-c5bd0194263b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.agents import initialize_agent, load_tools\n",
    "from langchain.agents import AgentType\n",
    "\n",
    "llm = ChatOpenAI(temperature=0)\n",
    "tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n",
    "agent = initialize_agent(\n",
    "    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84094a4a-1d76-461c-bc37-8c537939b466",
   "metadata": {},
   "source": [
    "**Now we're ready to run the chain!**\n",
    "\n",
    "The docstring below hints ways you can configure the method to run."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "112d7bdf-7e50-4c1a-9285-5bac8473f2ee",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[0;31mSignature:\u001b[0m\n",
       "\u001b[0marun_on_dataset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0mdataset_name\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'str'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0mllm_or_chain_factory\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'MODEL_OR_CHAIN_FACTORY'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0;34m*\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0mconcurrency_level\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'int'\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0mnum_repetitions\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'int'\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0msession_name\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'Optional[str]'\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0mverbose\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'bool'\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m    \u001b[0mclient\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'Optional[LangChainPlusClient]'\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
       "\u001b[0;34m\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0;34m'Dict[str, Any]'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
       "\u001b[0;31mDocstring:\u001b[0m\n",
       "Run the chain on a dataset and store traces to the specified session name.\n",
       "\n",
       "Args:\n",
       "    client: Client to use to read the dataset.\n",
       "    dataset_name: Name of the dataset to run the chain on.\n",
       "    llm_or_chain_factory: Language model or Chain constructor to run\n",
       "        over the dataset. The Chain constructor is used to permit\n",
       "        independent calls on each example without carrying over state.\n",
       "    concurrency_level: The number of async tasks to run concurrently.\n",
       "    num_repetitions: Number of times to run the model on each example.\n",
       "        This is useful when testing success rates or generating confidence\n",
       "        intervals.\n",
       "    session_name: Name of the session to store the traces in.\n",
       "        Defaults to {dataset_name}-{chain class name}-{datetime}.\n",
       "    verbose: Whether to print progress.\n",
       "    client: Client to use to read the dataset. If not provided, a new\n",
       "        client will be created using the credentials in the environment.\n",
       "\n",
       "Returns:\n",
       "    A dictionary mapping example ids to the model outputs.\n",
       "\u001b[0;31mFile:\u001b[0m      ~/code/lc/lckg/langchain/client/runner_utils.py\n",
       "\u001b[0;31mType:\u001b[0m      function"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "?arun_on_dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6e10f823",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Since chains can be stateful (e.g. they can have memory), we need provide\n",
    "# a way to initialize a new chain for each row in the dataset. This is done\n",
    "# by passing in a factory function that returns a new chain for each row.\n",
    "chain_factory = lambda: initialize_agent(\n",
    "    tools,\n",
    "    llm,\n",
    "    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",
    "    verbose=False,\n",
    ")\n",
    "\n",
    "# If your chain is NOT stateful, your lambda can return the object directly\n",
    "# to improve runtime performance. For example:\n",
    "# chain_factory = lambda: agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "a8088b7d-3ab6-4279-94c8-5116fe7cee33",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processed examples: 1\r"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Chain failed for example c6bb978e-b393-4f70-b63b-b0fb03a32dc2. Error: This model's maximum context length is 4097 tokens. However, your messages resulted in 4097 tokens. Please reduce the length of the messages.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processed examples: 9\r"
     ]
    }
   ],
   "source": [
    "evaluation_session_name = \"Search + Calculator Agent Evaluation\"\n",
    "chain_results = await arun_on_dataset(\n",
    "    dataset_name=dataset_name,\n",
    "    llm_or_chain_factory=chain_factory,\n",
    "    concurrency_level=5,  # Optional, sets the number of examples to run at a time\n",
    "    verbose=True,\n",
    "    session_name=evaluation_session_name,  # Optional, a unique session name will be generated if not provided\n",
    ")\n",
    "\n",
    "# Sometimes, the agent will error due to parsing issues, incompatible tool inputs, etc.\n",
    "# These are logged as warnings here and captured as errors in the tracing UI."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdacd159-eb4d-49e9-bb2a-c55322c40ed4",
   "metadata": {
    "tags": []
   },
   "source": [
    "### Reviewing the Chain Results\n",
    "\n",
    "You can review the results of the run in the tracing UI below and navigating to the session \n",
    "with the title **\"Search + Calculator Agent Evaluation\"**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "136db492-d6ca-4215-96f9-439c23538241",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<a href=\"https://dev.langchain.plus\", target=\"_blank\" rel=\"noopener\">LangChain+ Client</a>"
      ],
      "text/plain": [
       "LangChainPlusClient (API URL: https://dev.api.langchain.plus)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# You can navigate to the UI by clicking on the link below\n",
    "client"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63ed6561-6574-43b3-a653-fe410aa8a617",
   "metadata": {},
   "source": [
    "## Running an Evaluation Chain\n",
    "\n",
    "Manually comparing the results of chains in the UI is effective, but it can be time consuming.\n",
    "It's easier to leverage AI-assisted feedback to evaluate your agent's performance.\n",
    "\n",
    "A few ways of doing this include:\n",
    "- Adding ground-truth answers as outputs to the dataset and evaluating relative to those references.\n",
    "- Evaluating the overall agent trajectory based on the tool usage and intermediate steps.\n",
    "- Evaluating performance based on 'context' such as retrieved documents or tool results.\n",
    "- Evaluating 'aspects' of the agent's response in a reference-free manner using targeted agent prompts.\n",
    "    \n",
    "Below, we show how to run an evaluation chain that compares the model output with the ground-truth answers.\n",
    "\n",
    "**Note: the feedback API is currently experimental and subject to change.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "35db4025-9183-4e5f-ba14-0b1b380f49c7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.evaluation.qa import QAEvalChain\n",
    "\n",
    "eval_llm = ChatOpenAI(model=\"gpt-4\")\n",
    "chain = QAEvalChain.from_llm(eval_llm)\n",
    "\n",
    "examples = []\n",
    "predictions = []\n",
    "run_ids = []\n",
    "for run in client.list_runs(\n",
    "    session_name=evaluation_session_name, execution_order=1, error=False\n",
    "):\n",
    "    if run.reference_example_id is None or not run.outputs:\n",
    "        continue\n",
    "    run_ids.append(run.id)\n",
    "    example = client.read_example(run.reference_example_id)\n",
    "    examples.append({**run.inputs, **example.outputs})\n",
    "    predictions.append(run.outputs)\n",
    "\n",
    "evaluation_results = chain.evaluate(\n",
    "    examples,\n",
    "    predictions,\n",
    "    question_key=\"input\",\n",
    "    answer_key=\"output\",\n",
    "    prediction_key=\"output\",\n",
    ")\n",
    "\n",
    "\n",
    "for run_id, result in zip(run_ids, evaluation_results):\n",
    "    score = {\"CORRECT\": 1, \"INCORRECT\": 0}.get(result[\"text\"], 0)\n",
    "    client.create_feedback(run_id, \"Accuracy\", score=score)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "8696f167-dc75-4ef8-8bb3-ac1ce8324f30",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<a href=\"https://dev.langchain.plus\", target=\"_blank\" rel=\"noopener\">LangChain+ Client</a>"
      ],
      "text/plain": [
       "LangChainPlusClient (API URL: https://dev.api.langchain.plus)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "daf7dc7f-a5b0-49be-a695-2a87e283e588",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
